from urllib.parse import parse_qs

from html_00_common_header import generate_common_header
from html_01_common_footer import generate_common_footer


def handle_select_range_path(self, parsed_path):
    query_params = parse_qs(parsed_path.query)
    question_type = query_params.get('type', [None])[0]
    if not question_type:
        self.send_error(400, '', '无效的题型参数')
        return
    # 找出该题型的所有题号
    type_questions = [q for q in self.questions if q['题目类型'] == question_type]
    if not type_questions:
        self.send_error(404, f'No questions found for type: {question_type}')
        return

    self.send_response(200)
    self.send_header('Content-type', 'text/html; charset=utf-8')
    self.end_headers()
    self.wfile.write((generate_common_header(f"请选择 {question_type} 的题号范围", "2") +
                      generate_body(question_type, type_questions) +
                      generate_common_footer()
                      ).encode('utf-8'))


def generate_body(question_type, type_questions):
    min_num = min(q['题号'] for q in type_questions)
    max_num = max(q['题号'] for q in type_questions)

    # 新增：计算10题一组的范围
    batch_buttons = ""
    for start in range(min_num, max_num + 1, 10):
        end = min(start + 9, max_num)
        batch_buttons += f"""
                <a href="/practice?type={question_type}&start={start}&end={end}" 
                   class="batch-button">
                    {start}-{end}题
                </a>
                """
    return f"""
<h1>请选择 {question_type} 的题号范围</h1>
<div class="batch-container">
    <h3>快速选择：</h3>
    {batch_buttons}
</div>
<form action="/practice" method="get">
    <input type="hidden" name="type" value="{question_type}">
    起始题号: <input type="number" name="start" min="{min_num}" max="{max_num}" required><br>
    结束题号: <input type="number" name="end" min="{min_num}" max="{max_num}" required><br>
    <input type="submit" value="开始练习">
</form>
<style>
    .batch-container {{
        margin-bottom: 20px;
    }}
    .batch-button {{
        display: inline-block;
        padding: 8px 15px;
        margin: 5px;
        background-color: rgba(102, 204, 255, 0.2);
        color: #66ccff;
        border: 1px solid #66ccff;
        border-radius: 4px;
        text-decoration: none;
        transition: all 0.2s;
    }}
    .batch-button:hover {{
        background-color: rgba(102, 204, 255, 0.4);
        transform: translateY(-2px);
    }}
</style>
"""
